package com.juyu.miliao.scheduler.service;

import com.juyu.miliao.scheduler.rabbitMQ.HostLineTimeSignOutMq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Set;

/**
 * 根据心跳时间维护主播登出状态
 */
@Component
public class HostLineTimeSignOutScheduler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private HostLineTimeSignOutMq hostLineTimeSignOutMq;

    private final Logger logger = LoggerFactory.getLogger("hostLineTimeSignOut");

    @Scheduled(fixedDelay = 1000 * 60, initialDelay = 1000 * 30)
    public void scheduler(){
        logger.info("主播在线状态心跳检测------开始");
        //5分钟心跳时间，如果没有收到新的在线同步请求则视为登出，但是后端判断登出要比心跳时间稍长一点
        //获取6分钟之前的时间戳毫秒
        long timestampLocalDateTime = LocalDateTime.now().minus(6, ChronoUnit.MINUTES)
                                                    .toInstant(ZoneOffset.of("+8")).toEpochMilli();
        Set<ZSetOperations.TypedTuple<String>> set= stringRedisTemplate.opsForZSet()
                .rangeByScoreWithScores("hostLineTimeSignOut",0,timestampLocalDateTime);
        if(set != null && set.size() > 0){
            logger.info("主播在线状态心跳检测------登出set::::::"+set.toString());
            set.forEach(i->{
//                System.out.println("value:"+i.getValue()+" score:"+i.getScore());
                hostLineTimeSignOutMq.sendSignOutMq(i.getValue());
                stringRedisTemplate.opsForZSet().remove("hostLineTimeSignOut",i.getValue());
            });
        }else{
            logger.info("主播在线状态心跳检测------set.size()=0");
        }
        logger.info("主播在线状态心跳检测------结束");
    }
}
